/*
 * Copyright 2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.magneato.aop;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
/*
 * Posts tweets when new article is created. See magneato.properties for configuration
 */
@Aspect
@Component
public class TweetInterceptor {
	@Value("${twitter.OAuthConsumerKey}")
	private String oAuthConsumerKey;

	@Value("${twitter.OAuthConsumerSecret}")
	private String oAuthConsumerSecret;

	@Value("${twitter.OAuthAccessToken}")
	private String oAuthAccessToken;

	@Value("${twitter.OAuthAccessTokenSecret}")
	private String oAuthAccessTokenSecret;

	@Value("${twitter.debug}")
	private boolean debug;

	private static TwitterFactory twitterFactory;

	private final Log _logger = LogFactory.getLog(TweetInterceptor.class);

	@PostConstruct
	public void init() {
		System.out.println("umask " + oAuthConsumerKey);
		if (oAuthConsumerKey != null && !oAuthConsumerKey.isEmpty()) {
			ConfigurationBuilder cb = new ConfigurationBuilder();
			cb.setDebugEnabled(debug).setOAuthConsumerKey(oAuthConsumerKey)
					.setOAuthConsumerSecret(oAuthConsumerSecret)
					.setOAuthAccessToken(oAuthAccessToken)
					.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);

			twitterFactory = new TwitterFactory(cb.build());
		}
	}


	@Before("execution(* org.magneato.mvc.PageController.save(..)) && args(request, response, name, title, templateName, parent)")
	public void tweet(HttpServletRequest request, HttpServletResponse response,
			String name, String title, String templateName, String parent) {

		System.out.println("tweet tweet " + this.twitterFactory);
		if (templateName.isEmpty()) {
			return; // update, do nothing
		}

		StringBuilder url = new StringBuilder();
		url.append(request.getScheme());
		url.append("://");
		url.append(request.getServerName());

		int port = request.getServerPort();
		if (port != 80) {
			url.append(":");
			url.append(port);
		}
		String context = request.getContextPath();
		if (!context.isEmpty()) {
			url.append("/");
			url.append(context);
		}
		url.append(name);
		url.append(".htm");

		try {
			
			if (twitterFactory != null) {
				Twitter twitter = twitterFactory.getInstance();
				Status status = twitter.updateStatus(title + " "
						+ url.toString());
				
				System.out.println("tweet tweet" + status.getText());
				_logger.info("Tweeted " +url + " status " + status.getText());
			}
		} catch (TwitterException e) {
			_logger.error(e.getLocalizedMessage());
		}
	}
}
